package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerDao;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
	
	@Autowired
	private CustomerDao customerDao;
	
	@Override
	public List<Customer> getNoAssociationCustomers() {
		
		return customerDao.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> getAssociationCustomers(String fixedAreaId) {
		
		return customerDao.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void setNoAssociationCustomers(String noAssociationCustomerIds,
			String fixedAreaId) {
		customerDao.clearAllAssociationForFixedArea(fixedAreaId);
		if (StringUtils.isBlank(noAssociationCustomerIds)) {
			return;
		}
		
		String[] strings = noAssociationCustomerIds.split(",");
		
		for (String  customerIds: strings) {
			int id = Integer.parseInt(customerIds);
			customerDao.setNoAssociationCustomers( id ,
					 fixedAreaId);
		}
	}

	@Override
	public void customerSave(Customer customer) {
		customerDao.save(customer);
		
	}

	@Override
	public Customer getCustomerByTelephone(String telephone) {
		return customerDao.findByTelephone(telephone);
	}

	@Override
	public Customer login(String telephone, String password) {
		
		return customerDao.findByTelephoneAndPassword(telephone,password);
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		
		return customerDao.findFixedAreaIdByAddress(address);
	}

}
